package mytest.ssw.www.core;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;


import android.widget.ProgressBar;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import mytest.ssw.www.api.ActionCallbackListener;
import mytest.ssw.www.api.Api;
import mytest.ssw.www.api.ApiImpl;
import mytest.ssw.www.api.ApiResponse;
import mytest.ssw.www.mylibrary.Contents;
import mytest.ssw.www.mylibrary.DeptNode;
import mytest.ssw.www.mylibrary.getTheContent;
import mytest.ssw.www.mylibrary.Student;
import mytest.ssw.www.mylibrary.StudentInfo;
import mytest.ssw.www.mylibrary.UserInfo;

/**
 * Created by 73409 on 2015/11/3.
 */
public class AppActionImpl implements AppAction {
    Context context;
    Api api;
    ProgressBar pb;


    public AppActionImpl(Context context) {
        this.context = context;
        this.api = new ApiImpl();
    }

    @Override
    public void register(String studentId, String password, ActionCallbackListener<Void> listener) {
        //检查数据，
        // 参数检查
        if (TextUtils.isEmpty(studentId)) {
            if (listener != null) {
                listener.onFailure(ErrorEvent.PARAM_NULL, "学号为空");
            }
            return;
        }
        if (TextUtils.isEmpty(password)) {
            if (listener != null) {
                listener.onFailure(ErrorEvent.PARAM_NULL, "密码为空");

            }
            return;
        }
        //进行注册与服务器连接
        //do something

    }

    @Override
    public void login(final String studentId, final String password, final ActionCallbackListener<Void> listener)
    {
        //检查studentId是否非法
        if (TextUtils.isEmpty(studentId)) {
            if (listener != null) {
                listener.onFailure(ErrorEvent.PARAM_NULL, "登录名为空");
            }
            return;
        }
        //检查password是否非法
        if (TextUtils.isEmpty(password)) {
            if (listener != null) {
                listener.onFailure(ErrorEvent.PARAM_NULL, "密码为空");
            }
            return;
        }
        //进行注册与服务器连接
        // 请求Api

            AsyncTask<Void, Void, ApiResponse<Void>> execute = new AsyncTask<Void, Void, ApiResponse<Void>>() {
                @Override
                protected ApiResponse<Void> doInBackground(Void... voids) {
      /*          TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                String imei = telephonyManager.getDeviceId();
                Log.v("imei", imei);
                */
                    return api.loginByApp(studentId, password);
                }

                @Override
                protected void onPostExecute(ApiResponse<Void> response) {
                    if (listener != null && response != null) {
                        if (response.isSuccess()) {
                            listener.onSuccess(null);
                        } else {
                            listener.onFailure(response.getResult(), response.getElement());
                        }
                    }else{
                        listener.onFailure("登录", "无响应");
                    }
                }
            }.execute();


    }

    @Override
    public  void GetSomeoneInfor(final String num,final ActionCallbackListener<ApiResponse<StudentInfo>> listener)
    {
     //
        new AsyncTask<Void, Void, ApiResponse<StudentInfo>>()
        {   @Override
            protected ApiResponse<StudentInfo> doInBackground(Void... voids)
            {
                return api.GetSomeoneInfo(num);
            }

            @Override
            protected void onPostExecute(ApiResponse<StudentInfo> response)
            {
                if (listener != null && response!= null)
                {
                    if(response.getContents()==null) {
                        // Log.i(response.getStudentInfo().getName(), "获取");
                        if (response.isSuccess()) {
                            //        Log.i("ApiResponse ", response.getResult());
                            listener.onSuccess(response);
                        } else {
                            listener.onFailure(response.getResult(), response.getResult());
                        }
                    }else {
                            listener.onFailure(response.getResult(), response.getResult());
                        }
                    }
                }
        }.execute();

    }
    @Override
    public void GetUserInfo(final String num, final ActionCallbackListener<ApiResponse<UserInfo>> listener) {

        AsyncTask<Void, Void, ApiResponse<UserInfo>> res = new AsyncTask<Void, Void, ApiResponse<UserInfo>>()
        {            @Override
            protected ApiResponse<UserInfo> doInBackground(Void... voids) {
                return api.GetUserInfo(num);            }
            @Override
            protected void onPostExecute(ApiResponse<UserInfo> response) {
                if (listener != null && response.getUserInfo()!= null) {
                    if (response.isSuccess()) {
                        listener.onSuccess(response);
                    } else {
                        listener.onFailure(response.getResult(), response.getResult());
                    }
                }
            }
        }.execute();
    }
    @Override
    public  void GetDeptNodeList(final ActionCallbackListener<List<DeptNode>> listener)
    {
        //获取部门节点
       new AsyncTask<Void, Void, List<DeptNode>>()
        {   @Override
            protected List<DeptNode> doInBackground(Void... voids)
            {
                return api.GetDeptNode();
            }

            @Override
            protected void onPostExecute(List<DeptNode> response)
            {
             //   Log.i("App: ", response.get(1).getFullName());
                if (listener != null && response!= null) {
                      if (response.get(1).getFullName()!=null)
                    {
                        //        Log.i("ApiResponse ", response.getResult());
                        listener.onSuccess(response);
                    } else {
                        listener.onFailure("failure", "empty");
                    }
                }
            }
        }.execute();

    }
    public void SearchInfo(final HashMap<String,String> map,final ActionCallbackListener <ApiResponse<List<Contents>>>listener)
    { //  Handler mHandler;

        new AsyncTask<Integer, Integer, ApiResponse<List<Contents>>>() {
            @Override
            protected ApiResponse<List<Contents>> doInBackground(Integer... params)
            {
                return api.SearchInfo(map);        }
            @Override
            protected void onPostExecute(ApiResponse<List<Contents>> response) {
                if (listener != null && response.getContents()!= null)
                {
                    if (response.getContents().size()!=0)
                    {             listener.onSuccess(response);
                        Log.d("SearchInfo", response.getTotalRecords());
                    }
                    else {
                        listener.onFailure(response.getResult(), response.getResult());
                              }
                }
            }

        }.execute();
            }
    public List<Contents> SearchInfor(final HashMap<String,String> map,final ActionCallbackListener <ApiResponse<List<Contents>>>listener)
    { //  Handler mHandler;
        List<Contents> us=new ArrayList<>();
        AsyncTask<Void, Void, ApiResponse<List<Contents>>> res=  new AsyncTask<Void, Void, ApiResponse<List<Contents>>>() {
            @Override
            protected ApiResponse<List<Contents>> doInBackground(Void... voids)
            {                    return api.SearchInfo(map);        }
            @Override
            protected void onPostExecute(ApiResponse<List<Contents>> response) {
                if (listener != null && response.getContents()!= null) {
                    if (Integer.parseInt(response.getTotalRecords())!=0) {
                        listener.onSuccess(response);
                    } else {
                        listener.onFailure(response.getResult(), response.getResult());
                    }
                }
            }

        }.execute();
        try {  us = res.get().getContents();}
        catch(Exception e) {}
        return us;
    }
    public void modifyStuInfo(final StudentInfo info,final ActionCallbackListener<ApiResponse<Student>> listener)
    {

        new AsyncTask<Integer, Integer, ApiResponse<Student>>() {
            @Override
            protected ApiResponse<Student> doInBackground(Integer... params) {

                return api.modifyStuInfo(info);        }
            @Override
            protected void onPostExecute(ApiResponse<Student> response) {
                if (listener!=null&& response!= null) {
                    if (response.isSuccess()) {
                        listener.onSuccess(response);
                    } else {
                        listener.onFailure(response.getResult(), response.getResult());
                    }
                }
            }

       }.execute();
    }
    @Override
    public  List<getTheContent>  GetTheContentList(final String reciver,final ActionCallbackListener<List<getTheContent>> listener)
    {
        //
        List<getTheContent> rst=new ArrayList<>();
        AsyncTask<Void, Void, List<getTheContent>> res=  new AsyncTask<Void, Void, List<getTheContent>>()
        {
            @Override
            protected List<getTheContent> doInBackground(Void... voids)
            {
                return api.GetTheContent(reciver);
            }

            @Override
            protected void onPostExecute(List<getTheContent> response)
            {
                //     Log.i("App: ", response.get(1).getNoticeContent());
                if (listener != null && response!= null) {
                    if (response!=null)
                    {
                        //        Log.i("ApiResponse ", response.getResult());
                        listener.onSuccess(response);
                    } else {
                        listener.onFailure("failure", "empty");
                    }
                }
            }
        }.execute();
        try {
            rst=  res.get();
        }
        catch (Exception e){}
        return  rst;
    }




    @Override
    public void sendpost(final String contentP,final String sendPersonNumP,final String receiverNumsP,final ActionCallbackListener<Void>  listener) {
        //检查studentId是否非法
        if (TextUtils.isEmpty(contentP)) {
            if (listener != null) {
                listener.onFailure(ErrorEvent.PARAM_NULL, "内容不能为空");
            }
            return;
        }
        if (TextUtils.isEmpty(receiverNumsP)) {
            if (listener != null) {
                listener.onFailure(ErrorEvent.PARAM_NULL, "发送人不能为空");
            }
            return;
        }
        // 请求Api
        new AsyncTask<Void, Void, ApiResponse<Void>>() {
            @Override
            protected ApiResponse<Void> doInBackground(Void... voids) {
                return api.sendPost(contentP, sendPersonNumP, receiverNumsP);
            }

//            @Override
//            protected void onPostExecute(ApiResponse<Void> response) {
//                if (listener != null && response != null) {
//                    if (response.isSuccess()) {
//                        listener.onSuccess(null);
//                    } else {
//                        listener.onFailure(response.getResult(), response.getElement());
//                    }
//                }
//            }
        }.execute();
    }
    @Override
    public String getNetworkInfo(Context context){
        // Context context = context.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null)
        {
            return null;
        }
        else
        {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0)
            {
                for (int i = 0; i < networkInfo.length; i++)
                {
                    Log.d("getNetworkInfoState",i + "===状态===" + networkInfo[i].getState());
                    Log.d("getNetworkInfoType","" +networkInfo[i].getTypeName());
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
                    {

                        return networkInfo[i].getTypeName();
                    }
                }
            }
        }
        return null;
    }

}


